let app = getApp();
const { config } = require('../../../common/utils/ws/ws-config.js');
const { qyWXCheckSeesion } = require('../../utils/ws/ws-wxwork');

Component({
  externalClasses: [
    'button-class',
    'title-class',
    'icon-class',
    'img-class'
  ],
  properties: {
    floatItems: {
      type: Array,
      value: [],
      observer(newVal) {
        for (let obj of newVal) {
          if (obj.type && obj.type == 6 && obj.show) {
            this._geCsInfo();
          }
        }
      },
    },
    bottom: {
      type: Number,
      value: 50, // 悬浮框距底部,默认50rpx
    },
    showBorder: {
      type: Boolean,
      value: false,
    },
  },
  data: {
    useTabbar: !(app.tabbarindex === 0 && app.siteInfo.tabbar_type === '1'),
    plugid: '',
    defaultIcon: {
      1: 'icon icon-dh',
      2: 'icon icon-xcx',
      3: 'icon icon-dn',
      4: 'icon icon--custom',
      5: 'icon icon-xiaochengxuma',
      6: 'icon icon-wx',
      7: 'icon icon-sy',
      8: 'icon icon-tx1',
      9: 'icon icon-fabu',
      10: 'icon icon-shouquan',
      11: 'icon icon-shj',
      0: 'icon icon-bzzx',
    },
    isWXWork: app.isWXWork,
  },
  methods: {
    onItemClick(e) {
      const index = e.currentTarget.dataset.index;
      const item = this.data.floatItems[index];
      const type = `${item.type}`;
      switch (type) {
        case '1':
          this._toCall(item);
          break;
        case '2':
          this._navigateToMiniProgram(item);
          break;
        case '3':
          this._navigateToWebview(item);
          break;
        case '5':
          this._saveImg(item);
          break;
        case '7':
          this._navigateTo(item);
          break;
        case '8':
          this._CopyText(item);
          break;
        case '9':
          this._shareToExternalContact(item);
          break;
        case '0':
          this._trigger(item);
          break;

        default:
          break;
      }
    },
    _navigateToMiniProgram(e) {
      let { appid = '', path = '', extraData = {}} = e;
      wx.navigateToMiniProgram({
        appId: appid,
        path,
        extraData,
      });
    },

    _toCall(e) {
      const { mobile: mobileExp } = app.util.phoneExp;
      let { tel = '' } = e;
      let telShow = tel;
      if (mobileExp.test(tel)) {
        telShow = tel.substring(0, 3) + '-' + tel.substring(3, 7) + '-' + tel.substring(7, 11);
      }
      wx.showActionSheet({
        itemList: [telShow, '呼叫'],
        success(res) {
          wx.makePhoneCall({
            phoneNumber: tel,
          });
        },
      });
    },

    _saveImg(e) {
      let { image = '' } = e;
      let { route: currentPath, options } = getCurrentPages().pop();
      let parsedOptions = app.util.parseOptions(options);
      let optionsArr = [];
      for (let key in parsedOptions) {
        if (parsedOptions.hasOwnProperty(key)) {
          let value = parsedOptions[key];
          optionsArr.push(`${key}=${value}`);
        }
      }
      if (image) {
        wx.previewImage({
          urls: [image],
        });
      } else {
        wx.showLoading({
          title: '加载中',
        });
        app.util.request({
          url: 'wxapp/home/getXcxQrcode',
          data: {
            currentPath: currentPath + '?' + optionsArr.join('&'),
            acid: app.siteInfo.acid,
          },
          cachetime: 0,
          success: function (res) {
            wx.hideLoading();
            res.data && res.data.data && wx.previewImage({
              urls: [res.data.data],
            });
          },
          fail: function (err) {
            wx.hideLoading();
            wx.showToast({
              title: '小程序码获取失败',
              icon: 'none',
            });
          },
        });
      }
    },

    _CopyText(e) {
      let { text = '' } = e;
      wx.showActionSheet({
        itemList: ['复制客服微信号'],
        success(res) {
          let { tapIndex } = res;
          if (tapIndex === 0) {
            wx.setClipboardData({
              data: text,
              success(res) {
                wx.showToast({
                  title: '已复制客服微信号',
                  icon: 'none',
                });
              },
            });
          }
        },
      });
    },

    _navigateTo(e) {
      let { url = '' } = e;
      app.util.navigateTo(url || config.appJson[0].homePage);
    },

    _navigateToWebview(e) {
      const module = app.siteInfo.appJson[app.tabbarindex].module;
      let { url = '' } = e;
      app.util.navigateTo(`/${module}/pages/web/web`, { url: url });
    },

    _trigger(e) {
      let { event = '' } = e;
      this.triggerEvent(event);
    },

    _startmessage: function (e) {
      // body...
    },

    _completemessage: function (e) {
      // -3006，当前已是好友，提示退出小程序进行对话。个人不再受到[服务通知]推送
      if (e.detail.errcode === -3006) {
        return wx.showModal({
          title: '提示',
          content: '您已添加该客服为您的微信好友，您可以在微信聊天界面-[服务通知]中添加客服企业微信进行对话',
        });
      }
      if (e.detail.errcode === -3005) {
        return wx.showToast({
          title: '客服消息发送失败',
          duration: 1500,
          icon: 'none',
        });
      }
      if (e.detail.errcode === -3008) {
        return wx.showToast({
          title: '当前配置没有客服人员',
          duration: 1500,
          icon: 'none',
        });
      }
      if (e.detail.errcode === 0) {
        wx.showToast({
          title: '消息已发送成功，请查看邀请通知',
          duration: 1500,
          icon: 'none',
        });
      }
    },

    _geCsInfo(e) { // 获取企业微信客服ID
      let that = this;
      app.util.request({
        url: 'common/wechatworker/geCsInfo',
        cachetime: 0,
        success: function (res) {
          res.data.data && res.data.data.status && that.setData({
            plugid: res.data.data.plugid,
          });
        },
        fail: function (err) {
          console.log(err);
        },
      });
    },

    _tabMiniCard(e) {
      let args = e.detail;
      let currentPath = '';
      let pages = getCurrentPages();
      pages.length > 0 && (currentPath = '/' + pages.pop().route);
      args.path && currentPath !== args.path
        && setTimeout(() => {
          app.util.navigateTo(args.path, args.query || '');
        }, 500);
    },

    _shareToExternalContact(e) {
      if (this.data.isWXWork) {
        qyWXCheckSeesion({
          success: () => {
            app.util.request({
              url: 'auth/session/copyright',
              success: (res) => {
                if (res.data && res.data.data) {
                  const appid = res.data.data.appid;
                  wx.qy.shareToExternalContact({
                    appid, // 小程序的appid
                    // title: '', // 小程序消息的title
                    // imgUrl: '', // 小程序消息的封面图
                    page: getCurrentPages().pop().route, // 小程序消息打开后的路径
                  });
                }
              },
            });
          },
          fail: () => {
            console.log('企业微信登录失败');
          },
        });
      }
    },

    _getUserInfo(e) {
      this.triggerEvent('getUserInfo', e.detail);
    }
  },
});
